/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.insurance.cis.daos;

import com.insurance.cis.connection.CisConnection;
import com.insurance.cis.models.Channel;
import com.insurance.cis.scos.ChannelSearchCondition;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author TruongLQ
 */
public class ChannelDao {

    public List<Channel> getChannels(ChannelSearchCondition sco) {
        List<Channel> channels = new ArrayList<>();

        final StringBuilder sql = new StringBuilder("select * from Channel");
        boolean first = false;
        Map<Integer, Object> parameters = new HashMap<>();
        int count = 0;
        if (sco == null || !sco.isEmptyCondition()) {
            sql.append(" where ");
            if (sco.getChannelID() != null) {
                sql.append("ChannelID = ? ");
                first = true;
                parameters.put(++count, sco.getChannelID());
            }
            if (sco.getChannelDesc()!=null&&!sco.getChannelDesc().isEmpty()) {
                if (first) {
                    sql.append(" and ");
                }
                sql.append("ChannelDesc like ?");
                parameters.put(++count, "%" + sco.getChannelDesc() + "%");
            }
        }

        try {
            PreparedStatement pst = CisConnection.getInstance()
                    .getSqlConnection().prepareStatement(sql.toString());
            for (Integer pos : parameters.keySet()) {
                pst.setObject(pos, parameters.get(pos));
            }
            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                channels.add(new Channel(rs.getInt(1), rs.getString(2)));
            }
            return channels;
        } catch (SQLException ex) {
            Logger.getLogger(ChannelDao.class.getName()).log(Level.SEVERE, null, ex);
            return channels;
        }

    }
    
    public boolean checkIDExist(String channelID) {
        final String SQL = "select * from Channel where ChannelID=?";
        try {
            PreparedStatement pst = CisConnection.getInstance().getSqlConnection()
                    .prepareStatement(SQL);
            pst.setString(1, channelID);
            ResultSet rs = pst.executeQuery();
            return rs.next();
        } catch (SQLException ex) {
            Logger.getLogger(ChannelDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    }
}
